package com.sencorsta.ids.core.tcp.http;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.sencorsta.ids.core.entity.ErrorMsg;
import com.sencorsta.ids.core.info.CodeList;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;

import com.alibaba.fastjson.JSONObject;
import com.sencorsta.ids.core.log.Out;
import io.netty.handler.codec.http.QueryStringDecoder;

/**
 * 　　* @description: Http处理程序
 * 　　* @author TAO
 * 　　* @date 2019/6/12 17:11
 *
 */
public abstract class HttpHandler {
    public String userId;

    protected String path;

    protected String contentType;
    protected String fileName;

    {
        path = getClass().getSimpleName().replace("Handler", "");
        path = "/" + Character.toLowerCase(path.charAt(0)) + path.substring(1);
    }

    public static String getIp(ChannelHandlerContext ctx) {
        Channel session = ctx.channel();
        SocketAddress remoteAddress = session.remoteAddress();
        if (remoteAddress instanceof InetSocketAddress) {
            String ip = session.remoteAddress().toString();
            return ip.substring(1, ip.indexOf(":"));
        }
        return null;
    }

    public String getPath() {
        return this.path;
    }

    public void setContentType(String contentType) {
        this.contentType=contentType;
    }

    public void setFileName(String fileName ) {
        this.fileName=fileName;
    }

    public String doPost(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.warn("undefine doPost : ", request.uri());
        HttpServerHandler.response(ctx, request, "403", HttpResponseStatus.NOT_FOUND,contentType,fileName);
        ctx.close();
        return null;
    }

    public String doGet(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        Out.warn("undefine doGet : ", request.uri());
        HttpServerHandler.response(ctx, request, "404", HttpResponseStatus.NOT_FOUND,contentType,fileName);
        ctx.close();
        return null;
    }

    public Boolean getValidate(ChannelHandlerContext ctx, FullHttpRequest request, JSONObject params) {
        return true;
    }

    public String error(int code, String msg) {
        JSONObject res = new JSONObject();
        res.put("code", code);
        res.put("msg", msg);
        return res.toJSONString();
    }

    public String error(ErrorMsg error) {
        JSONObject res = new JSONObject();
        res.put("code", error.code);
        res.put("msg", error.Msg);
        return res.toJSONString();
    }

    public String success(Object data) {
        JSONObject res = new JSONObject();
        res.put("code", CodeList.SUCCESS.code);
        res.put("msg", CodeList.SUCCESS.Msg);
        if (data != null) {
            res.put("data", data);
        }
        return res.toJSONString();
    }


    public String success() {
        return success(null);
    }

    public String redirectGET(String url){
        setContentType(HttpContentTypes.FOUND);
        return url;
    }

    public String redirectGETforever(String url){
        setContentType(HttpContentTypes.MOVED_PERMANENTLY);
        return url;
    }

    public String redirectGET(String url, JSONObject params){
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        StringBuilder prestr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = (String)params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr.append(key).append("=").append(value);
            } else {
                prestr.append(key).append("=").append(value).append("&");
            }
        }
        return redirectGET(url+"?"+prestr);
    }

    public String redirectGETforever(String url, JSONObject params){
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        StringBuilder prestr = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = (String)params.get(key);
            if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
                prestr.append(key).append("=").append(value);
            } else {
                prestr.append(key).append("=").append(value).append("&");
            }
        }
        return redirectGETforever(url+"?"+prestr);
    }

    public String redirectPOST(String url){
        setContentType(HttpContentTypes.TEXT_HTML);
        JSONObject params=new JSONObject();
        if (url.indexOf("?") >= 0) {
            QueryStringDecoder query = new QueryStringDecoder(url);
            Set<Map.Entry<String, List<String>>> set = query.parameters().entrySet();
            for (Map.Entry<String, List<String>> entry : set) {
                params.put(entry.getKey(),
                        entry.getValue().size() == 1 ? entry.getValue().get(0) : entry.getValue());
            }
        }
        return redirect(url,params);
    }

    public String redirectPOST(String url, JSONObject params){
        setContentType(HttpContentTypes.TEXT_HTML);
        if (url.indexOf("?") >= 0) {
            if (params==null){
                params=new JSONObject();
            }
            QueryStringDecoder query = new QueryStringDecoder(url);
            Set<Map.Entry<String, List<String>>> set = query.parameters().entrySet();
            for (Map.Entry<String, List<String>> entry : set) {
                params.put(entry.getKey(),
                        entry.getValue().size() == 1 ? entry.getValue().get(0) : entry.getValue());
            }
        }
        return redirect(url,params);
    }

    public static String redirect(String url, JSONObject params){
        StringBuilder builder=new StringBuilder();
        builder.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        builder.append("<HTML>");
        builder.append(" <HEAD><TITLE>sender</TITLE></HEAD>");
        builder.append(" <BODY>");
        builder.append("<form name=\"submitForm\" action=\""+url+"\" method=\"post\">");
        Iterator<String> it=params.keySet().iterator();
        while(it.hasNext()){
            String key=it.next();
            builder.append("<input type=\"hidden\" name=\""+key+"\" value=\""+params.get(key)+"\"/>");
        }
        builder.append("</from>");
        builder.append("<script>window.document.submitForm.submit();</script>");
        builder.append(" </BODY>");
        builder.append("</HTML>");
        return builder.toString();
    }


}
